from flask import Blueprint, request, make_response
import json
import time
import datetime
from database import R

from user.model import User
from course.model import Classtable

course_blue = Blueprint('course', __name__)


def getUid():
    uid = R.get(request.headers.get('token'))
    if uid is None:
        return None
    else:
        return uid


@course_blue.before_request
def before_eq():
    if getUid() is None:
        return {
                   'errmsg': 'token expired'
               }, 401


@course_blue.route('/api/classtable', methods=['GET'])
def query_table():
    if request.method == 'GET':
        uid = getUid()
        user = User.query.filter(User.id == uid).first()
        if user.school is None:
            return {
                       'errmsg': '用户未绑定学校'
                   }, 201

        if user.school == 'scauzj':
            objs = []
            with open('admin/classtable.json', 'r', encoding='utf-8')as f:
                objs = json.loads(f.read())['tables']
                f.close()
            d = []
            for i in range(len(objs)):
                if 'scauzj' == objs[i]['value']:
                    d = objs[i]['date'].split('-')
                    break

            startday = datetime.datetime(int(d[0]), int(d[1]), int(d[2]))
            jstr = request.args.get('range')
            jobj = json.loads(jstr)
            midday = (jobj['endTime'] + jobj['startTime']) / 2
            midday = time.localtime(midday / 1000)
            nowday = datetime.datetime(midday.tm_year, midday.tm_mon, midday.tm_mday)
            daycount = (nowday - startday).days
            week = daycount // 7

            delta = nowday - startday
            if delta.days < 0:
                return {
                           'errmsg': '当前还未开学'
                       }, 201

            classtable = Classtable.query.filter(Classtable.week == week + 1, Classtable.userid == uid).first()

            resp = make_response(classtable.data)
            resp.headers["Content-Type"] = 'application/json; charset=UTF-8'
            return resp
        elif user.school == 'ynnubs':
            objs = []
            with open('admin/classtable.json', 'r', encoding='utf-8')as f:
                objs = json.loads(f.read())['tables']
                f.close()
            d = []
            for i in range(len(objs)):
                if 'ynnubs' == objs[i]['value']:
                    d = objs[i]['date'].split('-')
                    break

            startday = datetime.datetime(int(d[0]), int(d[1]), int(d[2]))
            jstr = request.args.get('range')
            jobj = json.loads(jstr)
            midday = (jobj['endTime'] + jobj['startTime']) / 2
            midday = time.localtime(midday / 1000)
            nowday = datetime.datetime(midday.tm_year, midday.tm_mon, midday.tm_mday)
            daycount = (nowday - startday).days
            week = daycount // 7

            delta = nowday - startday
            if delta.days < 0:
                return {
                           'errmsg': '当前还未开学'
                       }, 201

            classtable = Classtable.query.filter(Classtable.week == week + 1, Classtable.userid == uid).first()

            resp = make_response(classtable.data)
            resp.headers["Content-Type"] = 'application/json; charset=UTF-8'
            return resp
        else:
            return {
                       'errmsg': '所选学校暂不支持'
                   }, 200
